class Pagination{
  constructor(options){

    this.options = Object.assign({data_num : 10},options)

    //content 是渲染数据的容器选择器
    this.content = $(this.options.content)
    //pagination 是分页器的选择器
    this.pagination = $(this.options.pagination)
    //datas 是要渲染的数据
    this.datas = this.options.data;
    //data_num 是一页展示多少条数据
    this.data_num = this.options.data_num

    //page_num  这些数据分成几页
    this.page_num = this.datas.length / this.data_num
    this.page_num = Math.ceil(this.page_num)

    this.start = 0

    this.renderBullets()
    this.renderDatas()

    this.bullets = $('.bullets')
    this.prevBtn = $('.prev')
    this.nextBtn = $('.next')

    this.colorChange()
    this.bindEvent()

  }

  renderBullets(){
    this.pagination.append(`
      <div class='prev'>上一页</div>
    `)
    for(let i=0;i<this.page_num;i++){
      this.pagination.append(`
        <div class='bullets'>${i+1}</div>
      `)
    }
    this.pagination.append(`
      <div class='next'>下一页</div>
    `)
  }

  renderDatas(){
    this.content.html('')
    for(let i = this.start ;i < this.start + this.data_num; i++){
      if(this.datas[i]===undefined){
        break;
      }
      this.content.append(`
        <li  class='goods'>
          <img class='lozad' src='${this.datas[i].src}'>
          <div class='title'>${this.datas[i].title}</div>
          <div class='price'>${this.datas[i].price}</div>
        </li>
      `)
    }
  }
  
  bindEvent(){
    this.bullets.each((index,item) =>{
      $(item).on('click', ()=>{

        this.start = index * this.data_num;
        
        console.log('start:',this.start);
        this.colorChange()
        for(let i=this.start;i<this.start + this.data_num;i++){
          this.renderDatas()
        }
        
      })
      
    })

    this.prevBtn.on('click',()=>{
      this.start -= this.data_num
      
      if(this.start < 0){
        this.start += this.data_num
      }
      this.renderDatas()
      this.colorChange()
    })
    this.nextBtn.on('click',()=>{
      this.start += this.data_num
      this.last = this.bullets
      if(this.start > this.datas.length){
        this.start -= this.data_num
      }
      this.renderDatas()
      this.colorChange()
    })
  } 

  colorChange(){
    this.bullets.each((index,item) =>{
      $(item).removeClass('active')
    })
    this.bullets.each((index , item) =>{
      if(this.start === index*this.data_num){
        $(item).addClass('active')
      }
    })
  }
}
